//
//  CantripOViewNode.m
//  CantripSDK
//
//  Created by James Callender on Mon Jul 21 2003.
//  Copyright (c) 2003 James Callender. All rights reserved.
//

#import "CantripOViewNode.h"


@implementation CantripOViewNode

- (id)init
{
    if (self = [super init])
    {
        children = [[NSMutableArray alloc] 
            initWithArray:[NSArray array]];
        parent = nil;
        nodeValue = nil;
    }
	
    return self;
}

- (id)initWithCoder:(NSCoder *)coder
{
    self = [super init];
    children = [[coder decodeObject] retain];
    nodeValue = [[coder decodeObject] retain];

    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder
{	
    [coder encodeObject:children];
    [coder encodeObject:nodeValue];
}

- (id)copyWithZone:(NSZone *)zone
{
	int i;
	CantripOViewNode *newMe = 
            [[CantripOViewNode alloc] init];
	[newMe setNodeValue:[nodeValue mutableCopy]];
	for (i = 0; i < [children count]; i++)
	{
		[newMe insertChild:[[children objectAtIndex:i] copyWithZone:zone] atIndex:i];
	}
	
	return newMe;
}

- (void)insertChild:(CantripOViewNode *)child atIndex:(int)index 
{
    [children insertObject:child atIndex:index];
    [child setParent:self];
}

- (void)insertChildren:(NSArray*)kids atIndex:(int)index 
{
    [children insertObjectsFromArray:kids atIndex:index];
    [children makeObjectsPerformSelector:@selector(setParent:) withObject:self];
}

- (int)indexOfChild:(CantripOViewNode *)child 
{
    return [children indexOfObject:child];
}

- (void)removeChild:(CantripOViewNode *)child
{
	[children removeObjectIdenticalTo:child];
}

- (void)removeFromParent
{
	[[self parent] removeChild:self];
}

- (NSArray *)children
{
	return children;
}

- (int)numberOfChildren
{
	return [children count];
}

- (CantripOViewNode *)firstChild
{
	return [children objectAtIndex:0];
}

- (CantripOViewNode *)lastChild
{
	return [children lastObject];
}

- (CantripOViewNode *)childAtIndex:(int)n
{
	return [children objectAtIndex:n];
}

- (void)setParent:(CantripOViewNode *)p
{
	parent = p;
}

- (CantripOViewNode *)parent
{
	return parent;
}

- (BOOL)isDescendantOfNode:(CantripOViewNode *)node 
{
    CantripOViewNode *p = self;
    while(p) 
    {
        if(p==node) return YES;
        p = [p parent];
    }
    return NO;
}

- (BOOL)isDescendantOfNodeInArray:(NSArray*)nodes 
{
    NSEnumerator *nodeEnum = [nodes objectEnumerator];
    CantripOViewNode *node = nil;
    while((node=[nodeEnum nextObject])) 
	{
        if([self isDescendantOfNode:node]) return YES;
    }
    return NO;
}

- (id)nodeValue
{
    return nodeValue;
}

- (void)setNodeValue:(id)value
{
    [nodeValue autorelease];
    nodeValue = [value retain];
}

@end
